<template>
  <div class="social-media-chart-container" ref="chartContainer">
    <div class="social-media-info">
      <div class="platform-details">
        <div class="platform-title">Social media platform</div>
        <div class="platform-review-count">1,091</div>
        <div class="platform-review-label">Total reviews</div>
      </div>
    </div>
    <div class="chart-container">
      <PieChart
        :option="optionAnnular1"
        :height="'1.4375rem'"
        :width="'4.1667rem'"
        ref="pieChart"
      ></PieChart>
    </div>
  </div>
</template>

<script>
import { fontChart } from "@/utils/echartPxToRem";
import PieChart from "@components/common/PieChart.vue";
export default {
  components: { PieChart },
  props: {},
  data() {
    return {
      optionAnnular1: {},
      screenWidth: window.innerWidth,
      resizeTimer: null // 用于防抖
    };
  },
  methods: {
    // 生成图表配置（核心：根据当前屏幕宽度确定状态）
    createChartOption() {
      const isSmallScreen = this.screenWidth <= 1150;
      const labelFontSize = isSmallScreen ? 9 : 11;

      return {
        tooltip: { trigger: "item" },
        legend: [
          {
            orient: "vertical",
            left: "0%",
            top: "50%",
            itemWidth: 16,
            itemHeight: 16,
            itemGap: 7,
            formatter: (name) => {
              const dataItem = this.optionAnnular1.series?.[0].data?.find(item => item.name === name);
              const value = dataItem ? dataItem.value : 0;
              return `${name}  {valueStyle|${value}}`;
            },
            textStyle: {
              color: "#454545",
              fontSize: 12,
              rich: {
                valueStyle: { fontWeight: "bold", fontSize: 12 }
              },
              padding: [0, 0, 0, 4],
            },
            data: [
              { name: "YouTube", icon: "image://" + require("@/assets/pieIcon/YouTube1.png"), textStyle: { color: "#454545" } },
              { name: "Reddit", icon: "image://" + require("@/assets/pieIcon/Reddit1.png"), textStyle: { color: "#454545" } },
              { name: "TikTok", icon: "image://" + require("@/assets/pieIcon/TikTok1.png"), textStyle: { color: "#454545" } },
            ],
            show: !isSmallScreen // 严格根据屏幕宽度控制显示
          },
          {
            orient: "vertical",
            left: "23%",
            top: "50%",
            itemWidth: 16,
            itemHeight: 16,
            itemGap: 7,
            formatter: (name) => {
              const dataItem = this.optionAnnular1.series?.[0].data?.find(item => item.name === name);
              const value = dataItem ? dataItem.value : 0;
              return `${name}  {valueStyle|${value}} `;
            },
            textStyle: {
              color: "#454545",
              fontSize: 12,
              rich: {
                valueStyle: { fontWeight: "bold", fontSize: 12 }
              },
              padding: [0, 0, 0, 4],
            },
            data: [
              { name: "Instagram", icon: "image://" + require("@/assets/pieIcon/Instagram1.png"), textStyle: { color: "#454545" } },
              { name: "X", icon: "image://" + require("@/assets/pieIcon/X1.png"), textStyle: { color: "#454545" } },
              { name: "LinkedIn", icon: "image://" + require("@/assets/pieIcon/LinkedIn1.png"), textStyle: { color: "#454545" } },
            ],
            show: !isSmallScreen // 严格根据屏幕宽度控制显示
          },
        ],
        series: [
          {
            name: "Access From",
            type: "pie",
            radius: ["26%", "90%"],
            center: ["75%", "50%"],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: "inside",
              formatter: (params) => `{icon_${params.name}|}\n{percentStyle|${params.percent}%}`,
              distance: 0,
              padding: [0, 0, 0, 0],
              rich: {
                icon_YouTube: { backgroundColor: { image: require("@/assets/pieIcon/YouTube.png") }, width: 21, height: 16, align: "center" },
                icon_Reddit: { backgroundColor: { image: require("@/assets/pieIcon/Reddit.png") }, width: 16, height: 16, align: "center" },
                icon_TikTok: { backgroundColor: { image: require("@/assets/pieIcon/TikTok.png") }, width: 16, height: 16, align: "center" },
                icon_Instagram: { backgroundColor: { image: require("@/assets/pieIcon/Instagram.png") }, width: 16, height: 16, align: "center" },
                icon_X: { backgroundColor: { image: require("@/assets/pieIcon/X.png") }, width: 16, height: 16, align: "center" },
                icon_LinkedIn: { backgroundColor: { image: require("@/assets/pieIcon/LinkedIn.png") }, width: 16, height: 16, align: "center" },
                percentStyle: {
                  padding: [0, 0],
                  width: 25,
                  height: 25,
                  align: "center",
                  verticalAlign: "middle",
                  fontSize: labelFontSize,
                  color: "#fff",
                },
              },
            },
            itemStyle: { borderWidth: 2, borderColor: "#fff" },
            emphasis: { scale: false, label: { show: false } },
            labelLine: { show: false },
            data: [
              { value: 219, name: "TikTok", itemStyle: { color: "#703058" } },
              { value: 200, name: "YouTube", itemStyle: { color: "#964076" } },
              { value: 177, name: "X", itemStyle: { color: "#BB4F93" } },
              { value: 176, name: "Instagram", itemStyle: { color: "#9F579B" } },
              { value: 164, name: "LinkedIn", itemStyle: { color: "#AF73AC" } },
              { value: 155, name: "Reddit", itemStyle: { color: "#CFABCD" } },
            ],
          },
        ],
      };
    },

    // 防抖处理 resize 事件，避免频繁触发
    handleResize() {
      clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        this.screenWidth = window.innerWidth;
        this.optionAnnular1 = this.createChartOption(); // 重新生成配置
        this.$nextTick(() => {
          // 强制 ECharts 实例重绘
          if (this.$refs.pieChart?.chartInstance) {
            this.$refs.pieChart.chartInstance.setOption(this.optionAnnular1);
          }
        });
      }, 100); // 100ms 防抖延迟
    },

    checkSwitchStatus() {
      console.log("从 props 获取的开关状态:", this.switchValue);
      if (this.$store?.state?.dashBoard) {
        console.log("从 Vuex 获取的开关状态:", this.$store.state.dashBoard.mediaSwitch);
      } else {
        console.log("Vuex 未正确初始化或无法访问 dashBoard 模块");
      }
    }
  },

  mounted() {
    this.checkSwitchStatus();
    // 初始化图表配置（关键：确保初始状态正确）
    this.optionAnnular1 = this.createChartOption();
    // 监听窗口大小变化（带防抖）
    window.addEventListener("resize", this.handleResize);
    // 监听 Vuex 状态（保留原始逻辑）
    this.$store?.watch(
      (state) => state.dashBoard.mediaSwitch,
      () => {
        this.$nextTick(() => {
          this.optionAnnular1 = this.createChartOption();
        });
      }
    );
  },

  beforeDestroy() {
    // 清理事件监听，避免内存泄漏
    window.removeEventListener("resize", this.handleResize);
    clearTimeout(this.resizeTimer);
  }
};
</script>

<style lang="scss" scoped>
.social-media-chart-container {
  position: relative;
  background: #fff;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  height: 1.9583rem;
  border-radius: 0.0556rem;
  border: 1px solid #cdcccc;

  .social-media-info {
    width: 1.875rem;
    height: 1.7708rem;
    margin: 24px 45px 32px 24px;

    .platform-details {
      margin-bottom: 32px;

      .platform-title {
        font-size: 0.1389rem;
        font-weight: 600;
        margin-bottom: 16px;
        color: #454545;
      }

      .platform-review-count {
        font-size: 0.1667rem;
        font-weight: 700;
        color: #232323;
        margin-bottom: 3px;
      }

      .platform-review-label {
        font-size: 0.0694rem;
        font-weight: 400;
        color: #454545;
      }
    }

    .platform-switch {
      display: flex;
      justify-content: space-between;

      .switch-label {
        font-size: 14px;
        font-weight: 600;
        color: #6a6969;
      }

      .el-switch {
        display: flex;
        align-items: center;
        justify-content: center;
        .el-switch__core {
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }

  .chart-container {
    position: absolute;
    top: 18px;
    left: 0;
    margin: 37px 24px;
  }
}
</style>